const express = require('express')
const pool = require('../../mysql/mysql')
const router = express.Router()
const Nodetonken = require('../../token/token')

//注册
router.post('/register',(req,res)=>{
  //先查询该用户是否存在
  let sql = ' select * from userFrom where user_name = ? and user_upwd = ?'
  pool.query(sql,[req.body.uname,req.body.upwd],(error,result)=>{
    if(error) throw error;
    //<=就不存在
    if(result.length<=0){
      //不存在就允许注册
      let sql2 = 'insert into userFrom (user_name,user_upwd) values (?,?)'
      pool.query(sql2,[req.body.uname,req.body.upwd],(err,results)=>{
        if(err)throw err;
        res.send({code:200,message:'注册成功'})
      })
    }else{
      //存在
      res.send({code:202,message:'用户已存在'})
    }
  })
})


//登录
router.post('/login',(req,res)=>{
  let sql = 'select * from userFrom  where user_name = ? and user_upwd = ?'
  pool.query(sql,[req.body.uname,req.body.upwd],(error,result)=>{
    if(error)throw error;
    if(result.length==0){
      res.send({code:202,message:'用户不存在'})
    }else{
      //存在还要返回一个token
      let encode = new Nodetonken(req.body.uname)
      let token = encode.gainToken()
      res.send({code:200,message:'ok',data:result,token})
    }
  })
})
module.exports = router